package com.hay.goods.service;

import com.hay.item.api.BrandApi;
import com.hay.item.api.CategoryApi;
import com.hay.item.api.GoodsApi;
import com.hay.item.api.SpecificationApis;
import com.hay.item.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @title: GoodsService
 * @Author HuangYan
 * @Date: 2020/7/30 15:47
 * @Version 1.0
 */
@Service
public class GoodsService {

    @Autowired
    private BrandApi brandApi;

    @Autowired
    private CategoryApi categoryApi;

    @Autowired
    private GoodsApi goodsApi;

    @Autowired
    private SpecificationApis specificationApis;

    public Map<String, Object> getItemPageData(Long id){
        Map<String, Object> model = new HashMap<>();

        // 根据spuId 查询spu
        Spu spu = goodsApi.querySpuById(id);

        // 根据spuId 查询spuDetail
        SpuDetail spuDetail = goodsApi.querySpuDetailBySpuId(id);

        // 根据分类查询分类
        List<Map<String, Object>> categories = new ArrayList<>();
        List<Long> ids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
        List<String> names = categoryApi.queryNamesByIds(ids);
        // 将分类id与分类名称组成一个map
        for (int i = 0; i < ids.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ids.get(i));
            map.put("name", names.get(i));
            categories.add(map);
        }

        // 根据spu中的brandId查询商品
        Brand brand = brandApi.queryBrandById(spu.getBrandId());

        // 根据cid3查询skus
        List<Sku> skus = goodsApi.querySkuListBySpuId(id);

        // 根据分类cid3查询组
        List<SpecGroup> groups = specificationApis.queryGroupWithParamByCid(spu.getCid3());

        // 查询特殊的规格参数
        Map<Long, String> paramMap = new HashMap<>();
        List<SpecParam> specParams = specificationApis.queryParams(null, spu.getCid3(), false, null);
        specParams.forEach(param -> {
            paramMap.put(param.getId(), param.getName());
        });

        model.put("spu", spu);
        model.put("spuDetail", spuDetail);
        model.put("categories", categories);
        model.put("brand", brand);
        model.put("skus", skus);
        model.put("groups", groups);
        model.put("paramMap", paramMap);
        return model;
    }

}
